package StudyCode.summary.mycollection;

import java.lang.reflect.Array;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class AddsThePassedNewValuesToTheEndOfThePassedArray {
	public static <E> E[] append(E[] array, E... newValues) {
		return append(true, array, newValues);
	}

	@SuppressWarnings("unchecked")
	public static <E> E[] append(boolean dropNulls, E[] array,
	                             E... newValues) {
		try {
			if (newValues == null || newValues.length < 1)
				return (E[]) (dropNulls ? Array.newInstance(array
						.getClass().getComponentType(), 0) : array);
			if (array == null) {
				if (newValues != null) {
					Class clazz = newValues.getClass();
					Class arrType = clazz.getComponentType();
					array = (E[]) Array.newInstance(arrType, 0);
				} else {
					return array;
				}
			}
			int nullItemCount = 0;
			if (dropNulls) {
				for (E e : array) {
					if (e == null)
						nullItemCount++;
				}
				for (E e : newValues) {
					if (e == null)
						nullItemCount++;
				}
			}
			int newSize = array == null ? newValues.length : array.length
					+ newValues.length - nullItemCount;
			E[] newArray = (E[]) Array.newInstance(newValues.getClass()
					.getComponentType(), newSize);
			int offset = 0;
			if (!dropNulls) {
				if (!(array == null && array.length < 1)) {
					System.arraycopy(array, 0, newArray, 0, array.length);
					offset = array.length;
				}
				System.arraycopy(newValues, 0, newArray, offset,
						newValues.length);
			} else {
				int index = 0;
				for (E e : array) {
					if (e != null) {
						newArray[index] = e;
						index++;
					}
				}
				for (E e : newValues) {
					if (e != null) {
						newArray[index] = e;
						index++;
					}
				}
			}
			return newArray;
		} catch (Exception e) {
			throw new RuntimeException("Failed to append", e);
		}
	}
}
